const App = {
    mixins: [Save],//配置文件，路径/utils/mixins.js
    data() {
        return {
            getYMDDate,
            dataForm1: {},
            dataForm2: [],
            dataForm3: [],
            dataForm4: [],
            dataForm: {
                Completion_Progress: 0,
            },
            childDataForm: [],
            multipleSelection: [],
            fileList: [],
            Colors: [
                { color: '#F56C6C', percentage: 10 },
                { color: '#E6A23C', percentage: 40 },
                { color: '#409EFF', percentage: 90 },
                { color: '#67C23A', percentage: 100 }
            ],
            showDialog: false,
            showDialog1: false,
            check: '',
            fileUrl: '',
            type:'0'
        };
    },
    mounted() {
        let ls_URL = window.location.href;
        this.check = getQueryObject(ls_URL, "check");// 获取 nodeKey 参数
        this.type = getQueryObject(ls_URL, "type") || '0';// 获取 nodeKey 参数
        this.getCategory();
    },
    computed: {
        Current_Progress() {
            return function (index) {
                let num = 0;
                for (let i = 0; i < index + 1; i++) {
                    num += parseInt(this.dataForm2[i].Completion_Progress)
                }
                return num;
            }
        }
    },
    methods: {
        getCategory() {
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryBySQLSerialNumberWithOriginal`,
                type: "POST",
                data: {
                    SQLSerialNumber: 't_project_node',
                    Condition: window.btoa(unescape(encodeURIComponent("%%,%%"))),
                    ExtensionCondition: window.btoa(unescape(encodeURIComponent("AND project_node.Project_Node_SerialNumber='" + this.nodeKey + "'"))),
                },
                success: (data) => {
                    data[0].Completion_Progress = Number(data[0].Completion_Progress);
                    this.dataForm1 = data[0];
                    console.log(data[0]);
                }, complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryBySQLSerialNumber`,
                type: "POST",
                data: {
                    SQLSerialNumber: 't_project_node_check',
                    Condition: window.btoa(unescape(encodeURIComponent(""))),
                    ExtensionCondition: window.btoa(unescape(encodeURIComponent("AND project_node_check.Project_Node_SerialNumber='" + this.nodeKey + "'"))),
                },
                success: (data) => {
                    this.dataForm4 = data;
                }, complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
            
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableName`,
                type: "POST",
                data: {
                    Data: 'project_node_log',
                    Condition: "Project_Node_SerialNumber='" + this.nodeKey + "'"
                },
                success: (data) => {
                    this.dataForm2 = data;
                }, complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            })
        },
        show(row) {
            this.dataForm3 = [];
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableName`,
                type: "POST",
                data: {
                    Data: 'project_node_log_attachment',
                    Condition: "Project_Node_Log_SerialNumber='" + row.Project_Node_Log_SerialNumber + "'"
                },
                success: (data) => {
                    this.dataForm3 = data;
                    this.showDialog = true;
                }, complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            })

        },
        preview(row) {
            this.fileUrl = photo + row.Attachment_URL;
            this.showDialog1 = true;
        },
        async download(row) {
            // if (row.Attachment_URL) {
            //     window.open(photo + row.Attachment_URL)
            // }
            let apiUrl = photo + row.Attachment_URL;
            let fileName = apiUrl.split('/').pop();
            try {
                const response = await fetch(apiUrl);
                const blob = await response.blob();
                const url = window.URL.createObjectURL(blob);

                const a = document.createElement('a');
                a.href = url;
                a.download = fileName || 'download';
                document.body.appendChild(a);
                a.click();

                // 清理
                setTimeout(() => {
                    document.body.removeChild(a);
                    window.URL.revokeObjectURL(url);
                }, 100);
            } catch (error) {
                console.error('下载失败:', error);
            }
        },
        success(row, res) {
            this.childDataForm.push({
                uid: row.uid,
                Project_Node_Log_SerialNumber: this.dataForm.Project_Node_Log_SerialNumber,
                Attachment_URL: res.fileName,
                Attachment_Name: row.name,
                Temp_Path: res.tempPath,
                Attachment_Type: '1'
            })
        },
        remove(row) {
            if (!Object.keys(row).some(item => item.includes('_Original'))) {
                this.childDataForm = this.childDataForm.filter(i => i.uid != row.uid);
            } else {
                let obj = this.childDataForm.filter(i => i.Attachment_SerialNumber == row.Attachment_SerialNumber)[0];
                obj.Row_Status = '1'
            }
        },
        async handleSubmit() {
            const allValid = await this.validateAllForms();
            if (allValid) {
                if (this.dataForm1.Completion_Progress == this.dataForm1.Completion_Progress_Original && this.dataForm1.Project_Node_Status != '4') {
                    this.$message({
                        message: '上传的进度没有增长',
                        type: 'warning'
                    });
                    return
                }
                this.loading = true;
                let ls_URL = window.location.href;
                const action = getQueryObject(ls_URL, "action");   // 获取 action 参数
                let lJSONObject_Data_Options = new Object();
                lJSONObject_Data_Options = JSON.parse(document.getElementById("MainTable").getAttribute("data-options"));

                let ls_MainTableName = lJSONObject_Data_Options.TableName;
                let ls_DataForm = lJSONObject_Data_Options.form;
                let ls_primary_key = lJSONObject_Data_Options.primary_key;

                //没有子表下面内容就会报错，try/catch抛出异常
                try {
                    //可能涉及多个子表
                    document.getElementById("ChildTable").querySelectorAll(".el-descriptions").forEach(item => {
                        if (item.hasAttribute('data-options')) {
                            let lJSONObject_ChildData_Options = new Object();
                            lJSONObject_ChildData_Options = JSON.parse(item.getAttribute("data-options"));

                            let ls_ChildTableName = lJSONObject_ChildData_Options.TableName;
                            let ls_ChildDataForm = lJSONObject_ChildData_Options.form;
                            // let ls_ParentTableName = lJSONObject_ChildData_Options.ParentTableName;
                            if (this[ls_DataForm][ls_primary_key]) {
                                this[ls_ChildDataForm].forEach(item => {
                                    item[ls_primary_key] = this[ls_DataForm][ls_primary_key];
                                })
                            }
                            //建立子表结构体
                            let JSONArray_ChildRecord = new Array();
                            JSONArray_ChildRecord = this[ls_ChildDataForm];
                            if (!this[ls_DataForm].Children) {
                                this[ls_DataForm].Children = new Object();
                            }
                            this[ls_DataForm].Children[ls_ChildTableName] = JSONArray_ChildRecord;
                        }
                    })
                } catch (error) {

                }
                //建立新增提交结构
                let lJSONObject_DataSet = new Object();
                if (action == 'Add') {
                    this[ls_DataForm].Completion_Progress = this.dataForm1.Completion_Progress - Number(this.dataForm1.Completion_Progress_Original);
                    this[ls_DataForm].Project_SerialNumber = this.dataForm1.Project_SerialNumber;
                    this[ls_DataForm].Project_Node_SerialNumber = this.dataForm1.Project_Node_SerialNumber;
                    if (this.dataForm1.Project_Node_Status == '4') {
                        this[ls_DataForm].Project_Node_Check_SerialNumber = this.dataForm1.Project_Node_Check_SerialNumber;
                    }
                    if (this.nodeKey) {
                        this[ls_DataForm].Parent_SerialNumber = this.nodeKey;
                    }
                    let lJSONArray_Record = new Array();
                    lJSONArray_Record.push(this[ls_DataForm]);
                    let lJSONObject_Table = new Object();
                    lJSONObject_Table[ls_MainTableName] = lJSONArray_Record;
                    lJSONObject_DataSet[action] = lJSONObject_Table;
                } else if (action == 'Modify') {
                    
                    const { add, modify } = this.deal(this[ls_DataForm]);
                    let lJSONArray_Record = new Array();
                    lJSONArray_Record.push(modify);

                    let lJSONObject_Table = new Object();
                    lJSONObject_Table[ls_MainTableName] = lJSONArray_Record;

                    lJSONObject_DataSet[action] = lJSONObject_Table;
                    lJSONObject_DataSet['Add'] = new Object();
                    if (add != null) {
                        let lJSONArray_Record_Add = new Array();
                        lJSONArray_Record_Add.push(add);

                        let lJSONObject_Table_Add = new Object();
                        lJSONObject_Table_Add[ls_MainTableName] = lJSONArray_Record_Add;

                        lJSONObject_DataSet['Add'] = lJSONObject_Table_Add;
                    }
                }
                $.ajax({
                    headers: requestHeaders(),
                    url: `${mh}/generalBusiness/queryMultiTableByCondition`,
                    type: "POST",
                    data: {
                        Data: JSON.stringify([{
                            tableName: 'project_node',
                            Condition: window.btoa(unescape(encodeURIComponent("Project_Node_SerialNumber='" + this.nodeKey + "'"))),
                        }, {
                            tableName: 'project',
                            Condition: window.btoa(unescape(encodeURIComponent("Project_SerialNumber='" + this.dataForm1.Project_SerialNumber + "'"))),
                        }]),
                    },
                    success: ({ project_node, project }) => {
                        if (this.dataForm1.Completion_Progress == 100) {
                            project_node[0].Project_Node_Status = '2';
                        } else {
                            project_node[0].Project_Node_Status = '1';
                        }
                        project[0].Project_Status = '4';
                        lJSONObject_DataSet['Modify'] = {
                            project_node, project
                        };
                        if (this.dataForm1.Project_Node_Status == '4') {
                            lJSONObject_DataSet['Add'].project_node_check= [{
                                Project_Node_SerialNumber: this.nodeKey,
                                Row_Status: '2'
                            }]
                        }
                        let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                        lJSONObject_DataSet['Add']['base_operation_log'] = [{
                            Operation_Type: '0',
                            Operation_Path: this.relativePath,
                            Operation_Main,
                            Operation_Interface: "generalSaveByRequestBody",
                            Operation_IP: getIpAddress()
                        }]
                        submitSave(lJSONObject_DataSet, (res) => {
                            if (res.Status == 'success') {
                                window.location.href = './index.html'
                            }
                            this.loading = false;
                        })
                        // $.ajax({
                        //     headers: requestHeaders("JSON"),
                        //     url: `${mh}/generalBusiness/generalSaveByRequestBody`,
                        //     method: "post",
                        //     data: JSON.stringify({
                        //         Data: lJSONObject_DataSet,
                        //     }),
                        //     success: (res) => {
                        //         if (res.Status == 'success') {
                        //             window.location.href = './index.html'
                        //         }
                        //     },
                        //     complete: (XMLHttpRequest) => {
                        //         this.loading = false;
                        //         requestPretreatment(XMLHttpRequest)
                        //     }
                        // });
                    }, complete: (XMLHttpRequest) => {
                        requestPretreatment(XMLHttpRequest);
                    },
                    dataType: "json",
                });

            } else {
                this.$message({
                    message: '存在未填写的必填项！',
                    type: 'warning'
                });
            }
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        async handleSubmit1(is) {
            if (is == '3') {
                this.$confirm('此操作将验收通过该项目节点,是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(() => {
                    this.dataForm1.Project_Node_Status = is;
                    this.dataForm1.Project_Node_Actual_End_Date = getYMDDate();
                    let lJSONObject_DataSet = {
                        Modify: {
                            project_node: [this.dataForm1]
                        },
                        Add: {
                            project_node_check: [{
                                Project_Node_SerialNumber: this.nodeKey,
                                Row_Status: '0'
                            }]
                        }
                    }
                    $.ajax({
                        headers: requestHeaders(),
                        url: `${mh}/generalBusiness/queryMultiTableByCondition`,
                        type: "POST",
                        data: {
                            Data: JSON.stringify([{
                                tableName: 'project_node',
                                Condition: window.btoa(unescape(encodeURIComponent("Row_Status='0' AND Project_SerialNumber='" + this.dataForm1.Project_SerialNumber + "' AND Project_Node_SerialNumber <> '" + this.nodeKey + "'"))),
                            }, {
                                tableName: 'project',
                                Condition: window.btoa(unescape(encodeURIComponent("Project_SerialNumber='" + this.dataForm1.Project_SerialNumber + "'"))),
                            }]),
                        },
                        success: ({ project_node, project }) => {
                            if (project_node.every(i=>i.Project_Node_Status == is)) {
                                project[0].Project_Status = '6'
                                lJSONObject_DataSet['Modify'].project = project;
                            }
                            let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                            lJSONObject_DataSet['Add']['base_operation_log'] = [{
                                Operation_Type: '0',
                                Operation_Path: this.relativePath,
                                Operation_Main,
                                Operation_Interface: "generalSaveByRequestBody",
                                Operation_IP: getIpAddress()
                            }]
                            submitSave(lJSONObject_DataSet, (res) => {
                                if (res.Status == 'success') {
                                    window.location.href = './index.html'
                                }
                                this.loading = false;
                            })
                            // $.ajax({
                            //     headers: requestHeaders("JSON"),
                            //     url: `${mh}/generalBusiness/generalSaveByRequestBody`,
                            //     method: "post",
                            //     data: JSON.stringify({
                            //         Data: lJSONObject_DataSet,
                            //     }),
                            //     success: (res) => {
                            //         if (res.Status == 'success') {
                            //             window.location.href = './index.html'
                            //         }
                            //     },
                            //     complete: (XMLHttpRequest) => {
                            //         this.loading = false;
                            //         requestPretreatment(XMLHttpRequest)
                            //     }
                            // });
                        },
                        complete: (XMLHttpRequest) => {
                            requestPretreatment(XMLHttpRequest);
                        },
                    });
                }).catch(() => { });
            } else if (is == '4') {
                this.$prompt("请输入拒绝原因", '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                    inputPattern: /^\s*\S.+$/,
                    inputErrorMessage: "请输入拒绝原因"
                }).then(({ value }) => {
                    this.dataForm1.Project_Node_Status = is;
                    let lJSONObject_DataSet = {
                        Modify: {
                            project_node: [this.dataForm1]
                        },
                        Add: {
                            project_node_check: [{
                                Project_Node_SerialNumber: this.nodeKey,
                                Reason: value,
                                Row_Status: '1'
                            }]
                        }
                    }
                    let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                    lJSONObject_DataSet['Add']['base_operation_log'] = [{
                        Operation_Type: '0',
                        Operation_Path: this.relativePath,
                        Operation_Main,
                        Operation_Interface: "generalSaveByRequestBody",
                        Operation_IP: getIpAddress()
                    }]
                    submitSave(lJSONObject_DataSet, (res) => {
                        if (res.Status == 'success') {
                            window.location.href = './index.html'
                        }
                        this.loading = false;
                    })
                    // $.ajax({
                    //     headers: requestHeaders("JSON"),
                    //     url: `${mh}/generalBusiness/generalSaveByRequestBody`,
                    //     method: "post",
                    //     data: JSON.stringify({
                    //         Data: lJSONObject_DataSet,
                    //     }),
                    //     success: (res) => {
                    //         if (res.Status == 'success') {
                    //             window.location.href = './index.html'
                    //         }
                    //     },
                    //     complete: (XMLHttpRequest) => {
                    //         this.loading = false;
                    //         requestPretreatment(XMLHttpRequest)
                    //     }
                    // });
                }).catch(() => { });
            }
        },
    },
};
const { createApp, ref } = Vue;
const app = createApp(App);
app.use(ElementPlus, { locale: zhCn });
//这种方式是引入全部图标，无需单个引入
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component);
}
app.component('yl-upload', ylUpload);
app.component('yl-cascader', ylCascader);
app.component('yl-select', ylSelect);
app.component('yl-text-editor', ylTextEditor);
app.component('yl-online-preview', ylOnlinePreview);
const ElMessage = ElementPlus.ElMessage;
app.mount("#app");
